﻿using System;
using System.Collections.Generic;
using System.Text;

using Obsidian.Utils;
using Obsidian.Edm;
using Obsidian.Data.Sql;
using Obsidian.Data.Sql.SqlSrvClient;
using Oak.Model;

namespace Oak.MagSys.Data
{
    public class AdminMenuItemDA
    {

        internal int UpdteAdminMenuItemsByAdminId(long adminId, ICollection<MsAdminMenuItemInfo> items)
        {
            MsAdminMenuItemInfo i = new MsAdminMenuItemInfo();
            string sqlDelText = "DELETE FROM [{0}] WHERE [{1}] = {2} ";
            string sqlInsertText = "INSERT [" + i.DbTableName 
                + "] ([" + i.AdminId.DbFieldName 
                + "],[" + i.MenuItemId.DbFieldName 
                + "],[" + i.Created.DbFieldName + "]) VALUES ({0},{1},'{2}')";
            sqlDelText = String.Format(sqlDelText, i.DbTableName, i.AdminId.DbFieldName, adminId);
            StringBuilder sb = new StringBuilder();
            sb.Append(sqlDelText);
            foreach (MsAdminMenuItemInfo item in items)
            {
                sb.AppendLine(String.Format(sqlInsertText,
                    adminId, item.MenuItemId.Value, item.Created.ToString()));
            }
            string sqlText = sb.ToString();
            SqlSrvExecutor exr = new SqlSrvExecutor(i.GetDataBase().ConnectionString);
            return exr.ExecuteNonQuery(sqlText);
        }


        internal List<MsAdminMenuItemInfo> SelectList(MsAdminMenuItemQry qry)
        {
            MsAdminMenuItemInfo i = new MsAdminMenuItemInfo();
            MsMenuItemInfo m = i.MenuItem.New();
            IDbHandler dbh = i.CreateHandler();
            dbh.SetFields(i.Fields);
            dbh.SetFields(m.Fields);

            dbh.Join(m).On(i.MenuItemId.Equals(m.ItemId));

            if (!qry.AdminId.IsNull)
                dbh.Where(i.AdminId.Equals(qry.AdminId.Value));

            if (!qry.IsSystemMenuItem.IsNull)
                dbh.Where(m.IsSystemMenuItem.Equals(qry.IsSystemMenuItem.Value));

            dbh.OrderBy(m.Depth, OrderType.ASC);
            dbh.OrderBy(m.SortOrder, OrderType.ASC);

            DataReader dr = dbh.Select();
            List<MsAdminMenuItemInfo> list = new List<MsAdminMenuItemInfo>();
            while (dr.Read())
            {
                MsAdminMenuItemInfo item = new MsAdminMenuItemInfo();
                dr.ReadTo(item, item.MenuItem.New());
                list.Add(item);
            }
            dr.Close();
            return list;
        }

    }
}
